﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;

namespace TlvLib.PacketParsers
{
    public class LicensePlateParser
    {
        private  static Encoding encoding;

        static LicensePlateParser()
        {
            encoding = Encoding.GetEncoding("GB2312");
        }

        public bool CanParse(RawPacket packet)
        {
            return packet.PacketType == PacketType.LicensePlateInfo;
        }

        public LicensePlateInfo Parse(RawPacket packet)
        {
            var stream = new MemoryStream(packet.Payload);
            var reader = new MiscUtil.IO.EndianBinaryReader(Config.EndianBitConverter, stream);

            var m = reader.ReadInt32();
            var c = reader.ReadInt32();
            var r = reader.ReadInt32();

            var buffer = reader.ReadBytes(16);
            var plate = encoding.GetString(buffer).Replace("\0", "");
            
            var x = reader.ReadInt32();
            var y = reader.ReadInt32();
            var w = reader.ReadInt32();
            var h = reader.ReadInt32();

            var confidence = reader.ReadInt32();
            var pColor = reader.ReadInt16();
            var carType = reader.ReadInt16();
            var carColor = reader.ReadInt16();
            var wrongDir = reader.ReadByte();
            var detectMethod = reader.ReadByte();
            var speed = reader.ReadInt32();
            var speedLimit = reader.ReadInt32();
            var packId = reader.ReadBytes(32);

            var imgCount = reader.ReadInt16();
            var imageDatas = new ImageData[imgCount];
            for (int i = 0; i < imgCount; i++)
            {
                var year = reader.ReadInt16();
                var month = reader.ReadInt16();
                var d = reader.ReadInt16();
                var hour = reader.ReadInt16();
                var mm = reader.ReadInt16();
                var s = reader.ReadInt16();
                var ms = reader.ReadInt16();
                var time = new DateTime(year,month,d,hour,mm,s,ms);

                var imglen = reader.ReadInt32();
                var imgBuffer = reader.ReadBytes(imglen);

                imageDatas[i] = new ImageData() {CaptureTime = time, ImageBuffer = imgBuffer};
            }

            var lpi = new LicensePlateInfo()
                          {
                              CameraNo = c,
                              Confidence = confidence,
                              Images = imageDatas,
                              MonitorId = m,
                              PlateNo = plate,
                              PlatePosition = new Rectangle(x, y, w, h),
                              RoadNo = r
                          };

            return lpi;
        }
    }
}
